package com.compass.doctor.dialog

import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import androidx.activity.viewModels
import androidx.core.widget.addTextChangedListener
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.compass.doctor.callback.OnCreateConsumableCallBack
import com.compass.doctor.callback.OnCustomButtonClick
import com.compass.doctor.databinding.DialogConsumableOrderBinding
import com.compass.doctor.databinding.LayoutConsumableHeadBinding
import com.compass.doctor.ui.home.adapter.ConsumableAddedAdapter
import com.compass.doctor.ui.home.adapter.ConsumableShowAdapter
import com.compass.doctor.ui.home.viewmodel.MedicalCareViewModel
import com.compass.framework.base.BaseDialog
import com.compass.framework.base.BaseDialogFragment
import com.compass.framework.ext.gone
import com.compass.framework.ext.onClick
import com.compass.framework.ext.toJson
import com.compass.framework.ext.visible
import com.compass.framework.model.Consumable
import com.compass.framework.model.CreateConsumable
import com.compass.framework.toast.TipsToast
import com.compass.framework.utils.BigDecimalUtils
import com.compass.framework.utils.LogUtil

/**
 * Description： 耗材订单
 * Date:2024/1/10 22:24
 */
class ConsumableOrderDialog {
    class Builder(activity: FragmentActivity,private val orderId:String,private var onCreateConsumableCallBack: OnCreateConsumableCallBack) : BaseDialogFragment.Builder<Builder>(activity) {

        private val layoutShowHeadBinding: LayoutConsumableHeadBinding =
            LayoutConsumableHeadBinding.inflate(LayoutInflater.from(activity))

        private val layoutAddedHeadBinding: LayoutConsumableHeadBinding =
            LayoutConsumableHeadBinding.inflate(LayoutInflater.from(activity))
        private val mBinding: DialogConsumableOrderBinding =
            DialogConsumableOrderBinding.inflate(LayoutInflater.from(activity))

        private lateinit var consumableShowAdapter: ConsumableShowAdapter
        private lateinit var consumableAddedAdapter: ConsumableAddedAdapter
        private var addedList: MutableList<Consumable> = mutableListOf()
        private var showList: MutableList<Consumable> = mutableListOf()

        private val medicalCareViewModel: MedicalCareViewModel by activity.viewModels()
        private var keyword: String = ""

        //耗材添加回调
        private var consumableAddClick: OnCustomButtonClick = object : OnCustomButtonClick {
            override fun onButtonCallBack(position: Int, msgType: String?) {
                val item = showList[position]
                var num = item.num.toInt()
                when (msgType) {
                    "MinusSign" -> {
                        if (num > 1) num--
                        item.num = num.toString()
                        consumableShowAdapter.notifyItemChanged(position + 1)
                    }

                    "plusSign" -> {
                        num++
                        item.num = num.toString()
                        consumableShowAdapter.notifyItemChanged(position + 1)
                    }

                    "add" -> {
                        if (deEmphasis(item)){
                            TipsToast.showTips("当前耗材已添加")
                            return
                        }

                        addedList.add(item)
                        consumableAddedAdapter.addItem(item)
                        LogUtil.e("http_data==${consumableAddedAdapter.getData().toJson()}")
                        setEmpty()
                    }

                }
            }
        }

        //耗材添加回调
        private var consumableDeleteClick: OnCustomButtonClick = object : OnCustomButtonClick {
            override fun onButtonCallBack(position: Int, msgType: String?) {
                addedList.remove(addedList[position])
                consumableAddedAdapter.setData(addedList)
                setEmpty()

            }
        }

        init {
            initView()
            iniData()
        }

        private fun initView() {
            setContentView(mBinding.root)
            setWidth(ViewGroup.LayoutParams.MATCH_PARENT)
            setHeight(ViewGroup.LayoutParams.WRAP_CONTENT)
            setAnimStyle(BaseDialog.AnimStyle.BOTTOM)
            gravity = Gravity.BOTTOM
            consumableShowAdapter = ConsumableShowAdapter()
            consumableAddedAdapter = ConsumableAddedAdapter()
            initShowHeadView()
            initAddedHeadView()
            mBinding.tvClose.onClick {
                dismiss()
            }
            mBinding.btnReset.onClick {
                //重置
                addedList.clear()
                consumableAddedAdapter.setData(addedList)
                setEmpty()
            }
            mBinding.btnSearch.onClick {
                keyword = mBinding.edtDiagnosis.text.toString().trim()
                medicalCareViewModel.getConsumable(keyword)
            }

            mBinding.rcyConsumable.apply {
                itemAnimator?.changeDuration = 0
                layoutManager = LinearLayoutManager(activity)
                adapter = consumableShowAdapter
            }
            consumableShowAdapter.setCustomBottomClick(consumableAddClick)

            mBinding.rcyAdded.apply {
                layoutManager = LinearLayoutManager(activity)
                adapter = consumableAddedAdapter
            }

            consumableAddedAdapter.setCustomBottomClick(consumableDeleteClick)
            mBinding.tvAccept.onClick {
                //生成订单操作
                if (consumableAddedAdapter.getData().isNotEmpty()){
                    onCreateConsumableCallBack.createConsumableCallBack(CreateConsumable(orderId,consumableAddedAdapter.getData()))
                }else{
                    TipsToast.showTips("请先选择耗材")
                }
            }
            mBinding.edtDiagnosis.addTextChangedListener {
                if (it.isNullOrEmpty())    getConsumable()
            }
            mBinding.edtDiagnosis.setOnEditorActionListener { _, actionId, _ ->
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {

                    getConsumable()
                }
                false
            }
        }

        private fun  getConsumable(){
            keyword = mBinding.edtDiagnosis.text.toString().trim()
            medicalCareViewModel.getConsumable(keyword)
        }

        private fun iniData() {
            getConsumable()
            medicalCareViewModel.consumableLiveData.observe(activity) {
                it?.let { list ->
                    for (item in list) {
                        item.num = "1"//设置默认数量
                    }
                    showList = list
                    consumableShowAdapter.setData(showList)
                }?:kotlin.run {
                    showList.clear()
                    consumableShowAdapter.setData(showList)
                }
                setEmpty()
            }
        }

        private fun initShowHeadView() {
            consumableShowAdapter.addHeadView(layoutShowHeadBinding.root)
            layoutShowHeadBinding.tvTotalPrice.visibility = View.INVISIBLE

        }

        private fun initAddedHeadView() {
            consumableAddedAdapter.addHeadView(layoutAddedHeadBinding.root)
            layoutAddedHeadBinding.tvTotalPrice.visibility = View.VISIBLE
        }

        private fun setEmpty() {
            if (consumableShowAdapter.getData()
                    .isEmpty()
            ) mBinding.emptyConsumable.visible() else mBinding.emptyConsumable.gone()

            if (consumableAddedAdapter.getData()
                    .isEmpty()
            ) mBinding.emptyView.visible() else mBinding.emptyView.gone()
            computationalCosts()
        }

        /**
         * 去重操作
         */
        private fun deEmphasis(consumable: Consumable) :Boolean {
            var has=false
            for (item in consumableAddedAdapter.getData()) {
                 if (item.id==consumable.id) has=true
            }
            return has
        }

        /**
         * 计算金额
         */
        private fun computationalCosts() {
            var drugsCost ="0"
            for (drug in consumableAddedAdapter.getData()) {
                drugsCost= BigDecimalUtils.add(BigDecimalUtils.mul(drug.num, drug.price,2),drugsCost,2)
            }

            mBinding.tvAllCost.text=drugsCost

        }

        fun dismissDialog() {
            dismiss()
        }
    }
}